package com.andy.blog.admin.service.impl;

import com.andy.blog.admin.dto.CommentReplyDTO;
import com.andy.blog.admin.dto.RecentCommentDTO;
import com.andy.blog.admin.dto.ReplyDTO;
import com.andy.blog.admin.service.CommentReplyBusService;
import com.andy.blog.admin.service.LikeBusService;
import com.andy.blog.admin.service.SensitiveBusService;
import com.andy.blog.common.core.redis.RedisCache;
import com.andy.blog.common.page.PageUtilsDTO;
import com.andy.blog.common.utils.DateUtils;
import com.andy.blog.common.utils.ServletUtils;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.common.utils.ip.AddressUtils;
import com.andy.blog.common.utils.ip.IpUtils;
import com.andy.blog.dal.domain.CommentDO;
import com.andy.blog.dal.domain.ReplyDO;
import com.andy.blog.dal.service.CommentReplyDalService;
import com.andy.blog.dal.vo.CommentReplyVO;
import com.andy.blog.dal.vo.ReplyVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by andy on 2023/7/21 16:50
 */
@Service("commentReplyBusService")
public class CommentReplyBusServiceImpl implements CommentReplyBusService , LikeBusService {

    @Resource
    private CommentReplyDalService commentReplyDalService;

    @Resource
    private SensitiveBusService sensitiveBusService;

    @Resource
    private RedisCache redisCache;

    @Override
    public void addCommentReply(CommentReplyVO commentReplyVO) {
        final String ip = IpUtils.getIpAddress();
        String provinceByIp = AddressUtils.getProvinceByIp(ip);
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();

        // 敏感信息加密
        commentReplyVO.setContent(sensitiveBusService.filter(commentReplyVO.getContent()));
        commentReplyVO.setOs(os);
        commentReplyVO.setBrowser(browser);
        commentReplyVO.setIpLocation(provinceByIp);

        // 判断是子评论还是父评论
        if (Objects.isNull(commentReplyVO.getCommentId())) {
            // 新增父级评论
            commentReplyDalService.addComment(commentReplyVO);
            return;
        }

        ReplyVO replyVO = new ReplyVO();
        replyVO.setCommentId(commentReplyVO.getCommentId());
        replyVO.setArticleId(commentReplyVO.getArticleId());
        replyVO.setReplyType(commentReplyVO.getCommentType());
        replyVO.setContent(commentReplyVO.getContent());
        replyVO.setFromUserId(commentReplyVO.getFromUserId());
        replyVO.setToUserId(commentReplyVO.getToUserId());
        replyVO.setFromNickName(commentReplyVO.getFromNickName());
        replyVO.setToNickName(commentReplyVO.getToNickName());
        replyVO.setFromAvatar(commentReplyVO.getFromAvatar());
        replyVO.setToAvatar(commentReplyVO.getToAvatar());
        replyVO.setPraiseNum(commentReplyVO.getPraiseNum());
        replyVO.setReplyId(commentReplyVO.getReplyId());
        commentReplyDalService.addReply(replyVO);
    }

    @Override
    public PageUtilsDTO<CommentReplyDTO> listPage(CommentReplyVO commentReplyVO) {
        // 1. 获取所有的父评论
        IPage<CommentDO> commentDOIPage = commentReplyDalService.selectCommentByPage(commentReplyVO);

        List<CommentDO> records = commentDOIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return PageUtilsDTO.build(0L, new ArrayList<>());
        }

        List<CommentReplyDTO> commentReplyDTOS = TransformUtils.transformList(records, CommentReplyDTO.class);

        List<ReplyDO> replyDOS = commentReplyDalService.selectReplyList(commentReplyVO);
        Map<Long, List<ReplyDO>> listMap = replyDOS.stream().collect(Collectors.groupingBy(ReplyDO::getCommentId));
        for (CommentReplyDTO commentReplyDTO : commentReplyDTOS) {
            commentReplyDTO.setCreateTimeStr(DateUtils.transformToDay(commentReplyDTO.getCreateTime()));
            commentReplyDTO.setReplyVOList(listMap.get(commentReplyDTO.getId()));
        }

        return PageUtilsDTO.build(commentDOIPage.getTotal(), commentReplyDTOS);
    }

    @Override
    public List<ReplyDTO> listReply(Long commentId) {
        CommentReplyVO commentReplyVO = new CommentReplyVO();
        commentReplyVO.setCommentId(commentId);

        List<ReplyDO> replyDOS = commentReplyDalService.selectReplyList(commentReplyVO);

        List<ReplyDTO> replyDTOS = TransformUtils.transformList(replyDOS, ReplyDTO.class);

        Optional.ofNullable(replyDTOS).orElse(Lists.newArrayList()).forEach(s -> s.setCreateTimeStr(DateUtils.transformToDay(s.getCreateTime())));

        return replyDTOS;
    }

    @Override
    public List<RecentCommentDTO> listRecentCommentVO() {
        List<CommentDO> commentDOS = commentReplyDalService.listRecentComment();
        return TransformUtils.transformList(commentDOS, RecentCommentDTO.class);
    }

    @Override
    public void addOrCancelLike(Long commentId) {
        // 判断评论是否存在或是否通过或是否进入回收站
        //Comment comment = commentMapper.selectOne(new LambdaQueryWrapper<Comment>()
        //        .select(Comment::getId, Comment::getIsCheck)
        //        .eq(Comment::getId, commentId).last("limit 1"));
        //Assert.isFalse(Objects.isNull(comment) || comment.getIsCheck().equals(FALSE), "文章不存在");
        //// 用户id作为键，评论id作为值，记录用户点赞记录
        //String userLikeCommentKey = USER_COMMENT_LIKE + StpUtil.getLoginIdAsInt();
        //if (redisCache.hasSetValue(userLikeCommentKey, commentId)) {
        //    // 取消点赞则删除用户id中的评论id
        //    redisCache.deleteSet(userLikeCommentKey, commentId);
        //    // 评论点赞量-1
        //    redisCache.decrHash(COMMENT_LIKE_COUNT, commentId.toString(), 1L);
        //} else {
        //    // 点赞则在用户id记录评论id
        //    redisCache.setSet(userLikeCommentKey, commentId);
        //    // 评论点赞量+1
        //    redisCache.incrHash(COMMENT_LIKE_COUNT, commentId.toString(), 1L);
        //}
    }
}
